package com.test.controller;

import com.test.constant.ErrCode;
import com.test.exception.MyRuntimeException;
import com.test.model.rest.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by genghz on 17/6/23.
 */
@RestController
public abstract class BaseController {

    private static final Logger log = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private HttpServletResponse response;

    @ExceptionHandler(MyRuntimeException.class)
    public RestResponse badRequest(MyRuntimeException e) {
        log.warn("request has bad params: {}", e.getMessage());
        response.setStatus(e.getErrCode().code());
        return new RestResponse(e.getErrCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public RestResponse badRequest(Exception e) {
        log.warn("request has bad params: {}", e.getMessage());
        response.setStatus(ErrCode.INTERNAL_ERR.code());
        return new RestResponse(ErrCode.INTERNAL_ERR, e.getMessage());
    }
}
